import _puppeteer from 'puppeteer';
import { PuppeteerExtra } from 'puppeteer-extra';
import path from "path";
import app from './server';
import Streamer from './model/Streamer';
import { DYRecorder } from './DYRecorder';
import { delay } from './utils';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
import { book } from './DYRecorder';
import { sequelize } from './model/db';
 
import { recordMouseOperations } from './utils';
// 视窗和浏览器配置常量
 
const MAX_RECORDING = 1

async function main() {
  app.listen(3000);

  // 同步数据库结构
  try {
    console.log('正在同步数据库结构...');
    await sequelize.sync({ force: true });
    console.log('数据库同步完成');
  } catch (error) {
    console.error('数据库同步失败:', error);
  }

  // 初始化浏览器实例（整个应用共用）
  const puppeteer = new PuppeteerExtra(_puppeteer);
  puppeteer.use(StealthPlugin());

  const baseOptions = {
    headless: false as unknown as boolean,
    //defaultViewport: { width: VIEWPORT_WIDTH, height: VIEWPORT_HEIGHT, deviceScaleFactor: DEVICE_SCALE_FACTOR },
    defaultViewport: null,
    args: [
      '--disable-web-security',
      '--allow-file-access-from-files',
      "--autoplay-policy=no-user-gesture-required",
      "--disable-background-timer-throttling",
      '--disable-backgrounding-occluded-windows',
      '--disable-renderer-backgrounding',    
    ],
    timeout: 0
  };

  // 只启动一次浏览器
  const browser = await puppeteer.launch(baseOptions);
  // 创建专用的检测页面
 
  const patrol = await browser.newPage();
  while (1) {
    try {     
      const list = (await Streamer.findAll()).sort((a, b) => a.priority - b.priority);
      for (const item of list) {
        if (Object.keys(book).length >= MAX_RECORDING) {
          console.log(`已达到最大录制数量 ${MAX_RECORDING}，跳过检查`);
          // 将关闭页面改为跳转到空白页
          await patrol.goto('about:blank');
          break;
        }
        const url = `https://live.douyin.com/${item.liveId}`;
        const success = await patrol.goto(url, { timeout: 60000 })
          .then(() => true)
          .catch(e => {
            console.log(`访问 ${item.name} 的直播页面失败:`, e);
            return false;
          });
        
        if (!success) continue;
        
        console.log("正在检测", item.name, "的直播状态");
        if (await DYRecorder.isStreaming(patrol)) {
          if (item.liveId && book[item.liveId] === undefined)
            book[item.liveId] = true;
       
          console.log(item.name, "正在直播"); 
          if (item.liveId && book[item.liveId] === true) {
            // 使用浏览器上下文隔离不同直播
            const streamOptions = {
              ...baseOptions,
              userDataDir: path.resolve(process.cwd(), "user_dir",Date.now().toString()),
            };
            const streamBrowser = await puppeteer.launch(streamOptions);
            // Create a page in the new browser instance
            const recordPage = await streamBrowser.newPage();
            await recordPage.exposeFunction("log", console.log);
             
            await recordPage.goto(url, { timeout: 1000 * 1000 });
            book[item.liveId] = new DYRecorder(recordPage, () => {
              if (item.liveId) {
                delete book[item.liveId];
              }
              streamBrowser.close();
            });
            (book[item.liveId] as DYRecorder).start();
          }
        }   
        await delay(1000);
      }
      // 将关闭页面改为跳转到空白页
      await patrol.goto('about:blank');
      await delay(1000 * 60);
    } catch (error) {
      console.error('主循环发生错误:', error);
      // 等待一段时间后继续循环，避免频繁报错
      await delay(1000 * 10);
    }
  }
}

// recordMouseOperations();
main();

